/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.groupbuy.common.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.app.dto.ShopCartOrderMergerDto;
import com.yami.shop.groupbuy.common.api.dto.ApiGroupUserDto;
import com.yami.shop.groupbuy.common.api.dto.ApiGroupUserOrderDto;
import com.yami.shop.groupbuy.common.bo.GroupOrderBO;
import com.yami.shop.groupbuy.common.dao.GroupOrderMapper;
import com.yami.shop.groupbuy.common.dao.GroupTeamMapper;
import com.yami.shop.groupbuy.common.enums.GroupOrderStatusEnum;
import com.yami.shop.groupbuy.common.enums.TeamStatusEnum;
import com.yami.shop.groupbuy.common.model.GroupOrder;
import com.yami.shop.groupbuy.common.model.GroupTeam;
import com.yami.shop.groupbuy.common.service.GroupOrderService;
import com.yami.shop.service.OrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author LGH
 * @date 2019-08-27 17:55:57
 */
@Service
@AllArgsConstructor
@Slf4j
public class GroupOrderServiceImpl extends ServiceImpl<GroupOrderMapper, GroupOrder> implements GroupOrderService {

    private final GroupOrderMapper groupOrderMapper;
    private final OrderService orderService;
    private final GroupTeamMapper groupTeamMapper;

    /**
     * 获取参团的用户列表
     *
     * @param groupTeamId 拼团单ID
     * @return ApiGroupUserDto列表
     */
    @Override
    public List<ApiGroupUserDto> listApiGroupUserDto(Long groupTeamId) {
        return groupOrderMapper.listApiGroupUserDto(groupTeamId);
    }

    /**
     * @CachePut 的作用 主要针对方法配置，能够根据方法的请求参数对其结果进行缓存，和 @Cacheable 不同的是，它每次都会触发真实方法的调用
     * @param userId 用户id
     * @param apiGroupUserOrderDto
     * @return
     */
    @Override
    @CachePut(cacheNames = "ApiGroupUserOrderDto", key = "#userId")
    public ApiGroupUserOrderDto putConfirmOrderCache(String userId, ApiGroupUserOrderDto apiGroupUserOrderDto) {
        return apiGroupUserOrderDto;
    }

    /**
     * @Cacheable 的作用 主要针对方法配置，能够根据方法的请求参数对其结果进行缓存
     * @param userId
     * @return
     */
    @Override
    @Cacheable(cacheNames = "ApiGroupUserOrderDto", key = "#userId")
    public ApiGroupUserOrderDto getConfirmOrderCache(String userId) {
        return null;
    }

    @Override
    @CacheEvict(cacheNames = "ApiGroupUserOrderDto", key = "#userId")
    public void removeConfirmOrderCache(String userId) {
    }

    @Override
    public int getUserUnGroupOrderCount(String userId, Long groupActivityId, Long prodId) {
        return groupOrderMapper.getUserUnGroupOrderCount(userId, groupActivityId,prodId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelGroupOrder(String orderNumber, int status) {
        GroupOrder groupOrder = groupOrderMapper.selectOne(new LambdaQueryWrapper<GroupOrder>().eq(GroupOrder::getOrderNumber, orderNumber));
        // 取消的订单未支付并且是团长订单，则失效拼团队伍
        if (Objects.equals(groupOrder.getStatus(), 0) && Objects.equals(groupOrder.getIdentityType(), 1)) {
            GroupTeam groupTeam = new GroupTeam();
            groupTeam.setGroupTeamId(groupOrder.getGroupTeamId());
            groupTeam.setStatus(3);
            groupTeamMapper.updateById(groupTeam);
        }
        return groupOrderMapper.cancelGroupOrder(orderNumber, status);
    }

    @Override
    public Integer getUserHadOrderCountByGroupProdId(String userId, Long groupActivityId) {
        return groupOrderMapper.getUserHadOrderCountByGroupProdId(userId, groupActivityId);
    }

    /**
     * 添加团购订单数据
     * @param mergerOrder
     * @param groupOrderBO 订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(ShopCartOrderMergerDto mergerOrder, GroupOrderBO groupOrderBO) {
        // 团购活动订单，先创建订单，然后创建团购活动订单
        orderService.submit(mergerOrder);

        Date now = new Date();
        // 插入拼团订单
        GroupOrder groupOrder = new GroupOrder();
        groupOrder.setGroupTeamId(groupOrderBO.getGroupTeamId());

        // 如果为团长，则需新建拼团团队
        if (groupOrderBO.getGroupTeamId() == 0) {
            GroupTeam groupTeam = new GroupTeam();
            groupTeam.setShareUserId(groupOrderBO.getShareUserId());
//            groupTeam.setGroupProdId(groupOrderBO.getGroupProdId());
            groupTeam.setProdId(groupOrderBO.getProdId());
            groupTeam.setGroupActivityId(groupOrderBO.getGroupActivityId());
            groupTeam.setJoinNum(1);
            groupTeam.setCreateTime(now);
            groupTeam.setUpdateTime(now);
            groupTeam.setShopId(groupOrderBO.getShopId());
            groupTeam.setStatus(TeamStatusEnum.WAITING_GROUP.value());
            groupTeam.setTotalPrice(groupOrderBO.getPayPrice());
            groupTeamMapper.insert(groupTeam);
            groupOrder.setGroupTeamId(groupTeam.getGroupTeamId());
        }

        groupOrder.setGroupActivityId(groupOrderBO.getGroupActivityId());
        groupOrder.setUserId(groupOrderBO.getUserId());
        groupOrder.setOrderNumber(groupOrderBO.getOrderNumber());
        groupOrder.setActivityProdPrice(groupOrderBO.getActivityProdPrice());
        groupOrder.setPayPrice(groupOrderBO.getPayPrice());
        groupOrder.setShopId(groupOrderBO.getShopId());
        groupOrder.setIdentityType(Objects.equals(groupOrderBO.getGroupTeamId(), 0L) ? 1 : 0);
        groupOrder.setStatus(GroupOrderStatusEnum.WAITING_PAY.value());
        groupOrder.setCreateTime(now);
        groupOrderMapper.insert(groupOrder);
    }
}
